import Vue from "vue";
import Api from "./api";
import FormData from "form-data";
import https from "https";

const DOMAIN_IMAGE = process.env.DOMAIN_IMAGE || "";
const DOMAIN_API = process.env.DOMAIN_API || "";

// let ossClient = null;
// let ossLasTime = 0; // 最后连接时间

// 获取图片路径

// 获取图片路径
Vue.prototype.$getImageUrl = (value, option) => {
    if (!value) {
        // url为空，直接返回域名
        return "";
    } else if (/^https?:\/\//.test(value)) {
        return value;
    } else if (/^data:image\//.test(value)) {
        return value;
    } else if (/^blob:/.test(value)) {
        return value;
    } else {
        // 文档地址
        // https://help.aliyun.com/document_detail/144582.html
        // https://www.alibabacloud.com/help/zh/doc-detail/183902.html

        let type = Object.prototype.toString.call(option);
        let url = DOMAIN_IMAGE + "/" + (value || "").replace(/^\/+/, "");

        if (type == "[object Object]") {
            // 对象
            // 合并数据,将 {resize:'w_800',rotate:45} 转换成 resize,w_800/rotate,45 的结构
            let query = [];

            Object.keys(option).map((key) => {
                query.push(key + "," + option[key]);
            });

            return url + "?x-oss-process=image/" + query.join("/");
        } else if (/.svg$/.test(value)) {
            // svg 的直接返回
            return url;
        } else {
            // 没有图，默认返回一般的缩略图
            const format = {
                original: "", // 原图
                largest: "?x-oss-process=image/format,webp/quality,q_90", // 最大
                preview: "?x-oss-process=image/resize,w_1200/format,webp", // 图片预览
                large: "?x-oss-process=image/resize,w_640/format,webp/quality,q_90", // 大图
                medium: "?x-oss-process=image/resize,w_320/format,webp/quality,q_90", // 中图
                small: "?x-oss-process=image/resize,h_200/format,webp/quality,q_90", // 小图
                mini: "?x-oss-process=image/resize,w_50/format,webp/quality,q_90", // 微缩图
            }[option || "medium"];

            if (typeof format !== "undefined") {
                return url + format;
            } else {
                const query = option.replace ? option.replace(/^\?+/, "") : "";
                return url + (query ? "?" + query : "");
            }
        }
    }
};

// 静态资源地址
Vue.prototype.$getStaticUrl = (filepath) => {
    if (filepath) {
        return (
            "https://img.podpartner.com/static/" + filepath.replace(/^\//, "")
        );
    } else {
        return "";
    }
};

export default ({ app, $axios }, inject) => {
    // axios默认配置
    $axios.defaults.timeout = 60000; // 超时时间
    // 跳过证书认证
    $axios.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false });

    // 路由请求拦截
    // http request 拦截器
    $axios.interceptors.request.use(
        (config) => {
            let formdata = new FormData();
            let data = config.data || {};
            let token = app.store.getters["getToken"];

            for (var key in data) {
                var type = Object.prototype.toString.call(data[key]);
                if (type == "[object Array]") {
                    formdata.append(key, JSON.stringify(data[key]));
                } else if (type == "[object Object]") {
                    formdata.append(key, JSON.stringify(data[key]));
                } else {
                    formdata.append(key, data[key]);
                }
            }

            // post 才传formdata，其他的拼接在url后面
            if (/post|put/.test(config.method)) {
                config.data = formdata;
                config.headers["Content-Type"] = "multipart/form-data";
            } else {
                config.params = { ...data };
                config.data = undefined;
            }

            config.headers.Authorization =
                config.headers.Authorization || `Bearer ${token}`;
            config.headers["Cache-Control"] = "no-cache";
            config.headers["timestamp"] = new Date().getTime();

            if (/^http:s?\/\//.test(config.url)) {
                // 有地址
            } else if (process.client && !/podpartner/.test(location.host)) {
                // 不是测试环境或生产环境，全走代理
            } else if (config.url.indexOf("/drawer/") == 0) {
                // node，则走代理
            } else {
                // 相对地址
                config.url = DOMAIN_API + config.url;
            }
            return config;
        },
        (error) => {
            return Promise.reject(error.response.config);
        }
    );

    // 路由响应拦截
    // http response 拦截器
    $axios.interceptors.response.use(
        (response = {}) => {
            return new Promise((resolve, reject) => {
                // token 过期
                const result = response.data || {};
                const remoeLise = [3001, 3041];

                if (remoeLise.indexOf(result.code) >= 0) {
                    app.store.dispatch("doLogout");
                }
                resolve(response.data);
            });
        },
        (error) => {
            console.log("http error:", error.request._currentUrl);
            return Promise.reject(error.response); // 返回接口返回的错误信息
        }
    );

    // http 请求
    Vue.prototype.$http = (name, req, config = {}) => {
        // 请求地址
        let reqData = Vue.prototype.$getApi(name, req, config) || {}; // api信息

        if (!reqData.url) {
            return Promise.resolve({ code: 400, msg: "Api name error" });
        } else {
            return new Promise((resolve, reject) => {
                let reqType = Object.prototype.toString.call(req); // 参数类型
                let url = reqData.url; // 请求地址
                let method = reqData.method.toUpperCase(); // 请求方式
                let data = {}; // 参数
                // let count = process.client ? 3 : 1; // 请求失败循环
                let count = 1; // 请求失败循环
                let doAjax = () => {
                    // if (name.indexOf("User.dashBoard") == 0) {
                    //     setTimeout(() => {
                    //         resolve({
                    //             code: 400,
                    //             msg: "Network connection error",
                    //         });
                    //     }, 1000); // 间隔1秒

                    //     return;
                    // }

                    const headers = config.token
                        ? { Authorization: `Bearer ${config.token}` }
                        : undefined;

                    $axios(
                        {
                            url: url,
                            method: method,
                            data: data,
                            headers: headers,
                        },
                        config
                    )
                        .then((result) => resolve(result))
                        .catch((error) => {
                            count -= 1;
                            if (count > 0) {
                                setTimeout(doAjax, 1000); // 间隔1秒
                            } else {
                                const data = (error || {}).data || {};
                                resolve({
                                    code: data.code || 400,
                                    msg:
                                        data.msg ||
                                        "Network connection has timed out.",
                                });
                            }
                        });
                };

                // 参数是数字、字符串类型
                if (
                    reqType == "[object String]" ||
                    reqType == "[object Number]"
                ) {
                    url = url.replace(/\/$/, "") + "/" + req;
                } else {
                    data = req;
                }

                doAjax();
            });
        }
    };

    // 获取url信息
    Vue.prototype.$getApi = (name, req, config = {}) => {
        // 请求地址
        if (!name) {
            return null;
        } else if (/^https?:\/\//.test(name)) {
            const method = (config || {}).method || "GET";
            return { url: name, method: method };
        } else {
            let option = name.match(/^([\w\d.]+)([\w\W]*)/) || [];
            let keys = option[1] || "";
            let parame = option[2] || "";

            let result = keys.split(".").reduce((obj, key) => {
                return obj ? obj[key] : null;
            }, Api);

            if (result) {
                // 多个/去重
                parame =
                    /^\//.test(parame) && /\/$/.test(result.url)
                        ? parame.replace(/^\//, "")
                        : parame;
                return {
                    url: result.url + parame,
                    method: result.method,
                };
            } else {
                return null;
            }
        }
    };

    // 设计器用户未登录素材上传
    // 设计器用户已登录素材上传
    // 用户素材管理素材上传
    // 设计器保存数据生成设计图片、模特
    // 同步到店铺生成模特图

    inject("http", Vue.prototype.$http);
    inject("getApi", Vue.prototype.$getApi);
};
